<?php
declare (strict_types=1);

namespace app\service;


use think\facade\Db;
use app\model\BaseModel;

/**
 * 角色
 * Class SysRoleService
 * @package app\service
 */
class SysRoleService
{

    /**
     * 角色列表
     * @param array $param 参数数组
     * @return json
     */
    public static function getSysRoleList($param)
    {
        $model = Db::table('sys_role')->alias('sr');
        if (!empty($param['roleName'])) {
            $model->where('sr.role_name', 'like', '%' . $param['roleName'] . '%');
        }
        $res = $model->leftJoin('sys_dept sd', 'sr.dept_id = sd.id')
            ->where('sr.is_del', 0)
            ->field('sr.id,sr.role_name as roleName,sr.remark,sd.dept_name as deptName,sr.create_time as createTime')
            ->paginate(['page' => $param['page'], 'list_rows' => $param['pageSize']])->toArray();
        if (empty($res)) {
            return json_ok((object)array(), 0);
        }
        $list = ['total' => $res['total'], 'currentPage' => $res['current_page'], 'lastPage' => $res['last_page'], 'data' => $res['data']];
        return json_ok($list, 0);

    }

    /**
     * 角色详情
     * @param string $sysRoleId 角色ID
     * @return json
     */
    public static function sysRoleDetails($sysRoleId)
    {
        $res = Db::table('sys_role')->alias('sr')
            ->leftJoin('sys_dept sd', 'sr.dept_id=sd.id')
            ->field('sr.id as roleId,sr.role_name as roleName,sr.remark as remark,sd.id as deptId,sd.dept_name as deptName')
            ->where('sr.id', $sysRoleId)
            ->where('sr.is_del', 0)
            ->find();
        if (empty($res)) {
            return json_ok((object)array(), 0);
        }
        return json_ok($res, 200);

    }

    /**
     * 角色新增
     * @param array $param 参数数组
     * @return json
     */
    public static function sysRoleAdd($param)
    {
        $menuIdList = [];
        foreach ($param as $key => $value) {
            if (strpos($key, 'layuiTreeCheck') !== false) {
                $menuIdList[] = $value;
            }
        }
        BaseModel::beginTrans();
        try {
            $data = [];
            $data['role_name'] = $param['roleName'];
            $data['dept_id'] = $param['deptId'];
            $data['remark'] = $param['remark'];
            $data['create_by'] = 1;
            $data['update_by'] = 1;
            $data['update_time'] = date('Y-m-d H:i:s', time());
            Db::name('sys_role')->save($data);
            $roleId = Db::name('sys_role')->max('id');
            //处理新增的权限
            foreach ($menuIdList as $key => $value) {
                $data = [];
                $data['role_id'] = $roleId;
                $data['menu_id'] = $value;
                $data['enable'] = 1;
                $data['create_by'] = 1;
                $data['update_by'] = 1;
                Db::name('sys_role_menu')->save($data);
            }
        } catch (\Exception $e) {
            BaseModel::rollbackTrans();
            return json_error(100, $e->getMessage());
        }
        BaseModel::commitTrans();
        return json_ok((object)array(), 200);
    }

    /**
     * 角色编辑
     * @param array $param 参数数组
     * @return json
     */
    public static function sysRoleEdit($param)
    {
        $isSysRoleId = Db::table('sys_role')->alias('sr')->where('id', $param['id'])->where('enable',1)->where('is_del', 0)->find();
        if (empty($isSysRoleId)) {
            return json_error(100, '记录不存在');
        }
        $menuIdList = [];
        foreach ($param as $key => $value) {
            if (strpos($key, 'layuiTreeCheck') !== false) {
                $menuIdList[] = $value;
            }
        }
        BaseModel::beginTrans();
        try {
            $data = [];
            //$data['role_name'] = $param['roleName'];
            $data['dept_id'] = $param['deptId'];
            $data['remark'] = $param['remark'];
            $data['role_name'] = $param['roleName'];
            $data['update_time'] = date('Y-m-d H:i:s', time());
            Db::name('sys_role')->where('id', $param['id'])->where('is_del', 0)->data($data)->update();
            //处理用户角色增删改查情况

            foreach ($menuIdList as $key => $value) {
                $record = Db::name('sys_role_menu')->where('role_id', $param['id'])->where('menu_id', $value)->find();
                if ($record) {
                    if ($record['is_del'] == 1) {
                        Db::name('sys_role_menu')->where('role_id', $param['id'])->where('menu_id', $value)->where('is_del', 1)->update(['is_del' => 0]);
                    }
                    if ($record['enable'] == 0) {
                        Db::name('sys_role_menu')->where('role_id', $param['id'])->where('menu_id', $value)->where('enable', 0)->update(['enable' => 1]);
                    }
                } else {
                    $data = [];
                    $data['role_id'] = $param['id'];
                    $data['menu_id'] = $value;
                    $data['enable'] = 1;
                    $data['create_by'] = 1;
                    $data['update_by'] = 1;
                    Db::name('sys_role_menu')->save($data);
                }
            }
            Db::name('sys_role_menu')->where('role_id', $param['id'])->where('is_del', 0)->where('menu_id', 'not in', $menuIdList)->update(['is_del' => 1]);
        } catch (\Exception $e) {
            BaseModel::rollbackTrans();
            return json_error(100, $e->getMessage());
        }
        BaseModel::commitTrans();
        return json_ok((object)array(), 200);
    }

    /**
     * 角色删除
     * @param string $sysRoleId 角色ID
     * @return json
     */
    public static function sysRoleDelete($sysRoleId)
    {

        BaseModel::beginTrans();
        try {
            Db::name('sys_role')->where('id', $sysRoleId)->update(['is_del'=> 1]);
            Db::name('sys_user_role')->where('role_id', $sysRoleId)->update(['enable'=> 0]);
            Db::name('sys_role_menu')->where('role_id', $sysRoleId)->update(['enable'=> 0]);
        } catch (\Exception $e) {
            BaseModel::rollbackTrans();
            return json_error(100, $e->getMessage());
        }
        BaseModel::commitTrans();
        return json_ok((object)array(), 200);
    }

}
